using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.ProductionSystem;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ThridGroup.ERP.Web.Controllers
{
    [Route("[controller]")]
    public class MaterialTypeController : AbpController
    {
        private readonly IMaterialTypeService _materialTypeService;
        private readonly ILogger<MaterialTypeController> _logger;

        public MaterialTypeController(
            IMaterialTypeService materialTypeService,
            ILogger<MaterialTypeController> logger)
        {
            _materialTypeService = materialTypeService;
            _logger = logger;
        }

        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            _logger.LogInformation("访问物料分类管理页面");
            return View();
        }

        [HttpGet]
        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id, int? parentId)
        {
            if (id.HasValue)
            {
                var model = await _materialTypeService.GetMaterialType(id.Value);
                return View(model);
            }
            
            ViewBag.ParentId = parentId ?? 0;
            return View(new MaterialTypeDto());
        }

        [HttpGet]
        [Route("GetMaterialTypes")]
        public async Task<IActionResult> GetMaterialTypes(string materialTypeName = null, bool? isEnable = null)
        {
            try
            {
                _logger.LogInformation("开始获取物料分类列表");
                var list = await _materialTypeService.GetMaterialTypes();

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(materialTypeName))
                {
                    list = list.Where(x => x.MaterialTypeName.Contains(materialTypeName)).ToList();
                }

                if (isEnable.HasValue)
                {
                    list = list.Where(x => x.IsEnable == isEnable.Value).ToList();
                }

                // 按ParentId和Index排序
                list = list.OrderBy(x => x.ParentId).ThenBy(x => x.Index).ToList();

                _logger.LogInformation($"成功获取物料分类列表，共{list?.Count ?? 0}条记录");
                return Json(new { code = 0, msg = "获取成功", data = list });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料分类列表失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        [HttpGet]
        [Route("Get/{id}")]
        public async Task<IActionResult> GetMaterialType(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取物料分类，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的物料分类ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                var model = await _materialTypeService.GetMaterialType(id);
                if (model == null)
                {
                    _logger.LogWarning($"未找到指定的物料分类，ID：{id}");
                    return Json(new { code = 1, msg = "未找到指定的物料分类" });
                }

                _logger.LogInformation($"成功获取物料分类，ID：{id}");
                return Json(new { code = 0, msg = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取物料分类失败，ID：{id}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Add")]
        public async Task<IActionResult> AddMaterialType([FromBody] MaterialTypeDto dto)
        {
            try
            {
                _logger.LogInformation($"开始添加物料分类：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                
                if (dto == null)
                {
                    _logger.LogWarning("添加物料分类时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.MaterialTypeName))
                {
                    _logger.LogWarning("添加物料分类时名称为空");
                    return Json(new { code = 1, msg = "分类名称不能为空" });
                }

                var id = await _materialTypeService.AddMaterialType(dto);
                _logger.LogInformation($"成功添加物料分类，ID：{id}");
                return Json(new { code = 0, msg = "添加成功", data = id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加物料分类失败：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> UpdateMaterialType([FromBody] MaterialTypeDto dto)
        {
            try
            {
                _logger.LogInformation($"开始更新物料分类：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                
                if (dto == null)
                {
                    _logger.LogWarning("更新物料分类时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (dto.Id <= 0)
                {
                    _logger.LogWarning($"更新物料分类时ID无效：{dto.Id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                if (string.IsNullOrWhiteSpace(dto.MaterialTypeName))
                {
                    _logger.LogWarning("更新物料分类时名称为空");
                    return Json(new { code = 1, msg = "分类名称不能为空" });
                }

                var id = await _materialTypeService.UpdateMaterialType(dto);
                _logger.LogInformation($"成功更新物料分类，ID：{id}");
                return Json(new { code = 0, msg = "更新成功", data = id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新物料分类失败：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除物料分类
        /// </summary>
        [HttpPost]
        [Route("DeleteMaterialType")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteMaterialType(int id)
        {
            _logger.LogInformation($"接收到删除请求，ID：{id}");

            try
            {
                // 参数验证
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的ID参数：{id}");
                    return Json(new { code = 1, msg = "无效的参数" });
                }

                // 检查记录是否存在
                var materialType = await _materialTypeService.GetMaterialType(id);
                if (materialType == null)
                {
                    _logger.LogWarning($"要删除的物料分类不存在，ID：{id}");
                    return Json(new { code = 1, msg = "要删除的记录不存在" });
                }

                // 检查是否存在子分类
                var materialTypes = await _materialTypeService.GetMaterialTypes();
                if (materialTypes.Any(x => x.ParentId == id))
                {
                    _logger.LogWarning($"物料分类（ID：{id}）存在子分类，无法删除");
                    return Json(new { code = 1, msg = "该分类下存在子分类，请先删除子分类" });
                }

                // 执行删除
                await _materialTypeService.DeleteMaterialType(id);
                
                _logger.LogInformation($"成功删除物料分类，ID：{id}");
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除物料分类时发生错误，ID：{id}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }
    }
} 